<template>
  <a-card class="general-card" title="商品订单" :bordered="false">
    <a-tabs @change="(val)=>{apiParams.orderStatus = val;}" :default-active-key="orderStatus">
      <a-tab-pane key="ALL" title="全部"></a-tab-pane>
      <a-tab-pane key="UNPAID" :title="'待支付（'+unPaidOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="UNDELIVERED" :title="'待发货（'+unDeliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="PARTS_DELIVERED" :title="'部分发货（'+partsDeliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="DELIVERED" :title="'待收货（'+deliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="TAKE" :title="'待使用（'+unTakeOrderNum+'）'"></a-tab-pane>
      <!--      <a-tab-pane key="REFUSE" title="售后中"></a-tab-pane>-->
      <a-tab-pane key="COMPLETED" title="已完成"></a-tab-pane>
      <a-tab-pane key="CANCELLED" title="已关闭"></a-tab-pane>
    </a-tabs>
    <!-- 搜索 -->
    <PickSearchColumn ref="PickSearchColumnRef" :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
            <a-button  @click="exportOrder">
              导出订单
            </a-button>
        </a-space>
      </a-col>
    </a-row>

    <div class="order-box">
      <div class="order-tab">
        <p style="width: 30%">订单详情</p>
        <p style="width: 10%">订单来源</p>
        <p style="width: 10%;">店铺名称</p>
        <p style="width: 10%">应付</p>
        <p style="width: 8%">买家ID</p>
        <p style="width: 8%">买家/收货人</p>
        <p style="width: 8%;">订单促销类型</p>
        <p style="width: 8%">订单状态</p>
        <p style="width: 8%">操作</p>
      </div>
      <div class="order-lists" v-if="columnsTableList && columnsTableList.length">
        <div class="order-item" v-for="(order, orderIndex) in columnsTableList" :key="orderIndex">
          <div class="header">
            <p>订单编号：<a-typography-text copyable bold><span style="color: #333;">{{order.sn}}</span></a-typography-text></p>
            <p>下单时间：<span style="color: #333;">{{order.createTime}}</span></p>
            <!--<p class="delete-order"></p>-->
          </div>
          <div class="body">
            <div style="width: 30%;line-height: 32px;">
              <div class="goods">
                <div v-for="(goods, goodsIndex) in order.orderItems" :key="goodsIndex">
                  <img class="hover-color" :src="goods.image" alt=""/>
                  <div class="goods-info">
                    <div style="width: 100%;" class="hover-color"><a-typography-text copyable bold>{{goods.name}}</a-typography-text></div>
                    <!--<div class="tag"></div>-->
                  </div>
                  <div class="goods-num">
                    <span class="global_color"> {{unitPrice(goods.goodsPrice, '￥')}} </span>
                    <span style="color: red;"> x{{goods.num}} </span></div>
                </div>
              </div>
            </div>
            <div style="width: 10%;line-height: 32px;"><a-badge style="margin-right: 5px" :color="customClientTypeList(order.clientType).color"></a-badge>{{customClientTypeList(order.clientType).label}}</div>
            <div style="width: 10%;line-height: 32px;">{{order.storeName}}</div>
            <div style="width: 10%;line-height: 32px;">{{unitPrice(order.flowPrice, '￥')}}</div>
            <div style="width: 8%;" break-all line-height-24px>{{order.memberId}}</div>
            <div style="width: 8%;line-height: 32px;">
              <router-link :to="'/detail/member-detail?id='+ order.memberId"> 
                <a-typography-text type="primary" >{{order.memberName}}</a-typography-text> 
              </router-link> 
            </div>
            <div style="width: 8%;line-height: 32px;"><a-badge style="margin-right: 5px" :color="orderPromotionTypeList(order.orderPromotionType).color"></a-badge>{{orderPromotionTypeList(order.orderPromotionType).label}}</div>
            <div style="width: 8%;line-height: 32px;"><a-badge style="margin-right: 5px" :color="customOrderStatusList(order.orderStatus).color"></a-badge>{{customOrderStatusList(order.orderStatus).label}}</div>
            <div style="width: 8%"><a-button type="text" status="success" @click="$openWindow({name: 'order-detail', query: {id: order.sn,}})">查看</a-button></div>
          </div>
        </div>
      </div>
      <a-empty v-else></a-empty>
    </div>
    <div class="paginationBox">
      <a-pagination :total="paginationParams.total" show-page-size :current="apiParams.pageNumber" :page-size="apiParams.pageSize"
                    @change="(number) => { apiParams.pageNumber = number; }" @page-size-change="(number) => {apiParams.pageSize = number; apiParams.pageNumber = 1;}"
      ></a-pagination>
    </div>




  </a-card>
</template>

<script setup lang="ts">
import {getOrderList,getOrderStatisticsVO} from '@/api/order';
import {exportExcel} from '@/components/excel/exportExcel';
import {PickSearchColumn} from '@pickmall/ui-v3-components';
import {ColumnsDataRule, MethodsRule, SearchRule} from '@/types/global';
import {unitPrice} from '@/utils/filters';
import {deliveryMethod, orderClientType, orderType, paymentMethod} from '@/utils/tools';
import {Message} from '@arco-design/web-vue';
import {onMounted, ref, watch} from 'vue';
import {useRouter} from 'vue-router';

const orderStatus = ref<string>('ALL');
  const apiParams = ref({
    pageNumber: 1,
    pageSize: 10,
    // orderType: 'NORMAL',
    orderStatus:orderStatus.value
  });
  const router = useRouter();
  const tablePageRef = ref('');
  const data = ref(Array);
  const unPaidOrderNum = ref<any>(0);
  const unDeliveredOrderNum = ref<any>(0);
  const unTakeOrderNum = ref<any>(0);
  const partsDeliveredOrderNum = ref<any>(0);
  const deliveredOrderNum = ref<any>(0);
  const PickSearchColumnRef = ref<any>();
  const columnsTableList = ref();
  // 分页的属性配置
  const paginationParams = ref({
    total: 0
  });
  // 订单状态枚举
  const customOrderStatusList = (type: string) => {
    let result = null as any;
    if (type === 'UNDELIVERED') {
      result = {label: '待发货', value: 'UNDELIVERED', color: 'orange'};
    } else if (type === 'UNPAID') {
      result = {label: '未付款', value: 'UNPAID', color: 'magenta'};
    } else if (type === 'PAID') {
      result = {label: '已付款', value: 'PAID', color: 'blue'};
    } else if (type === 'DELIVERED') {
      result = {label: '已发货', value: 'DELIVERED', color: 'cyan'};
    } else if (type === 'PARTS_DELIVERED') {
      result = { label: '部分发货', value: 'PARTS_DELIVERED', color: 'cyan' };
    }else if (type === 'CANCELLED') {
      result = {label: '已取消', value: 'CANCELLED', color: 'red'};
    } else if (type === 'COMPLETED') {
      result = {label: '已完成', value: 'COMPLETED', color: 'green'};
    } else if (type === 'TAKE') {
      result = {label: '待使用', value: 'TAKE', color: 'orangered'};
    } else if (type === 'STAY_PICKED_UP') {
      result = {label: '待自提', value: 'STAY_PICKED_UP', color: 'orangered'};
    }  else {
      result = {label: '', value: '', color: ''};
    }
    return result;
  };
  // 订单促销类型枚举
  const orderPromotionTypeList = (type: string) => {
    let result = null as any;
    if (type === 'NORMAL') {
      result = {label: '普通订单', value: 'NORMAL', color: 'orange'};
    } else if (type === 'PINTUAN') {
      result = {label: '拼团订单', value: 'PINTUAN', color: 'magenta'};
    }else if (type === 'GIFT') {
      result = {label: '赠品订单', value: 'GIFT', color: 'blue'};
    }else if (type === 'VIRTUAL') {
      result = {label: '核验订单', value: 'VIRTUAL', color: 'red'};
    }else if (type === 'KANJIA') {
      result = {label: '砍价订单', value: 'KANJIA', color: 'green'};
    } else if (type === 'POINTS') {
      result = {label: '积分订单', value: 'POINTS', color: 'orangered'};
    } else {
      result = {label: '', value: '', color: ''};
    }
    return result;
  };
  // 查询海选列表
  const columnsSearch: Array<SearchRule> = [
    {label: '订单编号', model: 'orderSn', disabled: false, input: true,},
    {label: '会员名称', model: 'buyerName', disabled: false, input: true,},
    {label: '下单时间', disabled: false, datePicker: {type: 'range',},},
    {label: '买家/收货人手机号后四位', model: 'consigneeMobile', disabled: false, input: true,},
    {label: '收件人姓名', model: 'shipName', disabled: false, input: true,},
    {label: '商品名称', model: 'goodsName', disabled: false, input: true,},
    {label: '订单促销类型', model: 'orderPromotionType', disabled: false, select: {options: orderType,},},
    // {label: '售后状态', model: 'afterSaleStatus', disabled: false, select: {options: afterSaleStatusList},},
    {label: '订单来源', model: 'clientType', disabled: false, select: {options: orderClientType},},
    {label: '付款方式', model: 'paymentMethod', disabled: false, select: {options: paymentMethod},},
    {label: '配送方式', model: 'deliveryMethod', disabled: false, select: {options: deliveryMethod,},}
  ];

  // 表格搜索列表
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '订单号',
      dataIndex: 'sn',
    },
    {
      title: '订单来源',
      dataIndex: 'clientType',
      slot: true,
      slotData: {
        badge: orderClientType,
      },
    },
    {
      title: '订单类型',
      dataIndex: 'orderPromotionType',
      slot: true,
      slotData: {
        badge: orderType,
      },
    },
    {
      title: '买家名称',
      dataIndex: 'memberName',
    },
    {
      title: '订单金额',
      dataIndex: 'flowPrice',
      currency: true,
    },
    {
      title: '下单时间',
      width: 200,
      dataIndex: 'createTime',
    },
  ];
  // 操作列表
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '查看',
        callback: 'orderDetail',
        type:"text" ,
        status:"success"
      },
    ],
  };


  const customClientTypeList = (type: string) => {
    let result = null as any;
    if (type === 'H5') {
      result = {value: 'H5', label: '移动端',color: 'purple',};
    } else if (type === 'PC') {
      result = {value: 'PC', label: 'PC端', color: 'blue',};
    } else if (type === 'WECHAT_MP') {
      result = {value: 'WECHAT_MP', label: '小程序端', color: 'green',};
    } else if (type === 'APP') {
      result = {value: 'APP', label: '移动应用端', color: 'magenta',};
    } else {
      result = {};
    }
    return result;
  };
  const customPayStatusList = (type: string) => {
    let result = null as any;
    if (type === "UNPAID") {
      result = "未付款";
    } else if (type === "PAID") {
      result = "已付款";
    }  else{
      result = "";
    }
    return result;
  };

  // 商品订单列表
  const getMyOrder = async () => {
    const res = await getOrderList(apiParams.value);
    if (res.data.success) {
      columnsTableList.value = res.data.result.records;
      paginationParams.value = res.data.result;
    }
  };

  // 导出
  const exportOrder = async () => {
    const exportTableData = ref([]);
    PickSearchColumnRef.value.data.formData.pageSize = 10000
    getOrderList(PickSearchColumnRef.value.data.formData).then(res => {
      if(res.data.success){
        exportTableData.value = res.data.result.records.map((key: any) => {
          key.customClientType = customClientTypeList(key.clientType).label;
          key.customPayStatus = customPayStatusList(key.payStatus);
          return key;
        });
        const titleObj = {
          "订单编号": "sn",
          "下单时间": "createTime",
          "客户名称": "memberName",
          "支付方式": "customClientType",
          "商品数量": "groupNum",
          "付款状态": "customPayStatus",
          "店铺": "storeName",
        };
        exportExcel(exportTableData.value, `商品订单`, titleObj, "商品订单");
      } else {
        Message.warning("导出订单失败，请重试")
      }

  })
  };
  const getOrderNum = async () => {
    const res = await getOrderStatisticsVO();
    if (res.data.success) {
      unPaidOrderNum.value = res.data.result.unPaidOrder;
      unDeliveredOrderNum.value = res.data.result.unDeliveredOrder;
      unTakeOrderNum.value = res.data.result.unTakeOrder;
      partsDeliveredOrderNum.value = res.data.result.partsDeliveredOrder;
      deliveredOrderNum.value = res.data.result.deliveredOrder;


    }
  };

  // 初始化监听
  watch(() => apiParams.value,
      (val)=>{
        getMyOrder();
      }, {deep: true, immediate: true}
  );

  onMounted(() => {
    getMyOrder();
    getOrderNum();
  })
</script>

<style lang="less" scoped>
  .export {
    margin: 10px 20px 10px 0;
  }

  .export-excel-wrapper {
    display: inline;
  }

  .order-box {
    .order-tab {
      width: 100%;
      height: 50px;
      background-color: #f3f4f5;
      color: #252931;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      p {
        flex-shrink: 0;
        text-align: center;
      }
    }
    .order-lists {
      .order-item {
        box-sizing: border-box;
        border: 1px solid #eeeff0;
        margin-bottom: 10px;
        font-size: 14px;
        .header {
          width: 100%;
          height: 50px;
          background-color: #f8f9fa;
          color: #333;
          display: flex;
          align-items: center;
          box-sizing: border-box;
          padding: 0 20px;
          position: relative;
          font-size: 14px;
          p {
            margin-right: 30px;
          }
          .delete-order {
            position: absolute;
            top: 3px;
            right: 0;
            margin-right: 0;
          }
        }
        .body {
          display: flex;
          align-items: stretch;
          justify-content: space-between;
          text-align: center;
          color: #252931;
          > div {
            flex-shrink: 0;
            box-sizing: border-box;
            padding: 14px 0;
            /*border-left: 1px solid #e5e5e5;*/
          }
          > div:nth-of-type(1) {
            border-left: none;
            padding: 0;
            text-align: left;
          }
          .goods {
            padding: 4px 0;
          }
          .goods > div {
            width: 100%;
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            /*border-bottom: 1px solid #e5e5e5;*/
            box-sizing: border-box;
            padding: 10px;
            position: relative;
            img {
              width: 56px;
              height: 56px;
              flex-shrink: 0;
              border-radius: 4px;
            }
            .goods-info {
              flex-shrink: 1;
              width: 100%;
              box-sizing: border-box;
              padding: 6px 15px;
              color: #252931;
              font-size: 14px;
              line-height: 18px;
              .tag {
                color: #aaaaaa;
                white-space: nowrap;
                margin-top: 12px;
                line-height: 12px;
                width: 100%;
                > span {
                  display: inline-block;
                }
                > span:nth-of-type(1) {
                  width: 126px;
                }
                > span:nth-of-type(3) {
                  color: #e4393c;
                  text-align: end;
                  position: absolute;
                  right: 10px;
                  bottom: 10px;
                }
              }
            }
            .goods-num {
              flex-shrink: 0;
              width: 25%;
              text-align: right;
            }
          }
          .goods > div:nth-last-of-type(1) {
            border-bottom: none;
          }
          .hover-color {
            /*overflow: hidden;*/
            /*-webkit-line-clamp: 2;*/
            /*text-overflow: ellipsis;*/
            /*display: -webkit-box;*/
            /*-webkit-box-orient: vertical;*/
            /*white-space: pre-wrap;*/
          }
        }
      }
    }
  }
  .paginationBox {
    margin-top: 18px;
    display: flex;
    flex-direction: row-reverse;
  }

  a{
    list-style: none !important;
    text-decoration:none !important;
    color: inherit !important;
  }
</style>
